<template>
  <div class="header">
    <div class="header-top">
      <router-link to="/">
        <div class="header-left">
          <span class="iconfont">&#xe624;</span>
        </div>
      </router-link>
      <h1>城市选择</h1>
    </div>
    <div class="header-search">
      <input type="text" placeholder="输入城市名或拼音" v-model="keyword">
    </div>
    <div class="city-list" v-show="keyword" ref="wrapper">
      <ul class="item-list">
        <li class="item"
            v-for="item in searchList"
            :key="item.id"
            @click="handleCityClick(item.name)"
        >{{ item.name }}</li>
        <li class="item" v-show="hasNoData">没有符合条件的城市</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bsroll from 'better-scroll'
export default {
  name: 'CityHeader',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      timer: null,
      searchList: []
    }
  },
  methods: {
    handleCityClick (name) {
      this.$store.dispatch('changeCity', name)
      this.$router.push('/')
    }
  },
  computed: {
    hasNoData () {
      return !this.searchList.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        var result = []
        for (var i in this.cities) {
          this.cities[i].forEach((item) => {
            if (item.spell.indexOf(this.keyword) > -1 ||
              item.name.indexOf(this.keyword) > -1) {
              result.push(item)
            }
          })
        }
        this.searchList = result
      }, 150)
    }
  },
  mounted () {
    this.scroll = new Bsroll(this.$refs.wrapper)
  }
}
</script>

<style scoped lang="less">
  @import "~styles/varibles";
.header-top{
  height: 0.68rem;
  line-height: 0.88rem;
  background-color: @bgColor;
  .header-left{
    height: 0.88rem;
    width: 0.64rem;
    float: left;
    text-align: center;
    .iconfont{
      margin-left: -0.05rem;
      color: white;
    }
  }
  h1{
    height: 0.88rem;
    margin: 0 1rem;
    text-align: center;
    font-size: 0.32rem;
    color: #fff;
  }
}
.header-search{
  height: 0.8rem;
  line-height: 0.8rem;
  background-color: @bgColor;
  input{
    width: 6rem;
    border-radius: 0.06rem;
    height: 0.5rem;
    padding: 0 0.1rem;
    text-align: center;
  }
}
.city-list{
  position: absolute;
  top: 1.48rem;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
  overflow: hidden;
  background-color: #fff;
  .item-list{
    padding: 0.1rem 0.3rem 0.1rem 0.3rem;
    .item{
      line-height: 0.6rem;
    }
  }
}
</style>
